﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBAC_Class.ErrorCode;
using RBAC_Class.Write.API.Application.Command.Roles;
using System;
using System.Threading.Tasks;
using NLog;

namespace RBAC_Class.Write.API.Controllers
{
    /// <summary>
    /// 角色控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<RoleController> logger;

        public RoleController(IMediator mediator, ILogger<RoleController> logger)
        {
            this.mediator = mediator;
            this.logger = logger;
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddRole(AddRoleCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加角色失败 - 角色名: {RoleName}", cmd.RoleName);
                throw;
            }
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> DeleteRole(DeleteRoleCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除角色失败 - 角色ID: {RoleID}", cmd.RoleID);
                throw;
            }
        }
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <returns>返回任务</returns>
        [HttpPost]
        public async Task<APIResult<int>> UpdateRole(UpdateRoleCommand cmd)
        {
            try
            {
                return await mediator.Send(cmd);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "修改角色失败 - 角色ID: {RoleID}, 角色名: {RoleName}", cmd.RoleID, cmd.RoleName);
                throw;
            }
        }
    }
}
